<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入商品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="图片地址" prop="productUrl">
        <el-input v-model="queryParams.productUrl" placeholder="请输入图片地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="排序" prop="urlSort">
        <el-input v-model="queryParams.urlSort" placeholder="请输入排序" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="图片类型" prop="picType">
        <el-select v-model="queryParams.picType" placeholder="请选择图片类型" clearable>
          <el-option v-for="dict in dict.type.product_pic_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="crTime">
        <el-date-picker clearable v-model="queryParams.crTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="upTime">
        <el-date-picker clearable v-model="queryParams.upTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['store:productpic:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['store:productpic:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['store:productpic:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['store:productpic:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="productpicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品id" align="center" prop="productId" />
      <el-table-column label="商品编码" align="center" prop="productCode" />
      <el-table-column label="图片地址" align="center" prop="productUrl">
        <template slot-scope="scope">
          <el-image style="width: 100px" :src="scope.row.productUrl" fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="urlSort" />
      <el-table-column label="图片类型" align="center" prop="picType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_pic_type" :value="scope.row.picType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="图片状态" align="center" prop="picFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pic_flag" :value="scope.row.picFlag"/>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.picFlag" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="crTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.crTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="upTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.upTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['store:productpic:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['store:productpic:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品图片对话框 -->
    <el-dialog :title="title" @close="cancel" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品编码" prop="productCode">
          <el-select v-model="form.productCode" placeholder="请选择商品编码" clearable>
            <el-option v-for="dict in shopList" :key="dict.productCode" :label="dict.productName"
              :value="dict.productCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="图片地址" prop="pLroductUrl">
          <el-upload class="upload-demo" action="" :on-preview="handlePreviewN" :on-remove="handleRemoveN" ref="upload"
            :before-remove="beforeRemoveN" :auto-upload="false" :multiple="isMultiple" :limit="limitNum" :on-change="fileChange"
            :on-success="handle_successN" :on-exceed="handleExceedN" :file-list="fileListN">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>

          <ul class="image-list">
            <li v-for="(item, index) in listNew" :key="index">
              <el-image style="width: 100px" :src="item.url" fit="fill"></el-image>
              <!-- <img :src="item.url" style="width: 100%;height: auto;" mode="aspectFill" :alt="item.name"> -->
                    <span style="font-size: 16px;" @click="deleteImage(index)">x</span>
              <!-- <img :src="item.url" :alt="item.name">
              <span @click="deleteImage(index)">删除</span> -->
            </li>
          </ul>
        </el-form-item>
        <el-form-item label="排序" prop="urlSort">
          <el-input v-model="form.urlSort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="图片类型" prop="picType">
          <el-select v-model="form.picType" placeholder="请选择图片类型">
            <el-option v-for="dict in dict.type.product_pic_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    uploadImages,
    fileDeleteOss,
    productinfoDiceList,
    productStatus
  } from "@/api/system/user";
  import {
    listProductpic,
    getProductpic,
    delProductpic,
    addProductpic,
    updateProductpic
  } from "@/api/store/productpic";
  import {
    getToken
  } from "@/utils/auth";

  export default {
    name: "Productpic",
    dicts: ['product_pic_type', 'pic_flag'],

    props: {
      value: [String, Object, Array],
      // 图片数量限制
      limit: {
        type: Number,
        default: 5,
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 5,
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
        type: Array,
        default: () => ["png", "jpg", "jpeg"],
      },
      // 是否显示提示
      isShowTip: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        limitNum:7,
        isMultiple:true,
        number: 0,
        uploadList: [],
        dialogImageUrl: "",
        dialogVisible: false,
        hideUpload: false,
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload/oss", // 上传的图片到云存储
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        fileList: [],
        fileListN: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品图片表格数据
        productpicList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          productCode: null,
          productUrl: null,
          urlSort: null,
          picType: null,
          crTime: null,
          upTime: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          productCode: [{
            required: true,
            message: '请选择活动编码1',
            trigger: 'blur'
          }, ],
          urlSort: [{
            required: true,
            message: '请选择活动编码2',
            trigger: 'blur'
          }, ],
          picType: [{
            required: true,
            message: '请选择活动编码3',
            trigger: 'blur'
          }, ]
        },
        // xlsFile:'',
        xlsFile: [],
        listNew: [],
        shopList: [],
        shopStatus: [],

      };
    },


    watch: {
      value: {
        handler(val) {
          if (val) {
            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',');
            // 然后将数组转为对象数组
            this.fileList = list.map(item => {
              if (typeof item === "string") {
                if (item.indexOf(this.baseUrl) === -1) {
                  item = {
                    name: this.baseUrl + item,
                    url: this.baseUrl + item
                  };
                } else {
                  item = {
                    name: item,
                    url: item
                  };
                }
              }
              return item;
            });
          } else {
            this.fileList = [];
            return [];
          }
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize);
      },
    },
    created() {
      this.getList();
      this.productinfoDiceList()
    },
    methods: {
      // 用户状态修改
      handleStatusChange(row) {
        console.log(typeof(row.picFlag))
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认该操作吗？').then(function() {
          return productStatus(row.picFlag, row.productId);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      productinfoDiceList(index) {
        productinfoDiceList().then(res => {
          if (res.code == '200') {
            console.log(this.form,'--------')
            this.shopList = res.data
          }
        });

      },

      deleteImage(index) {
        console.log(index,'000')
        console.log(this.listNew,'34')
        let res = this.listNew[index].url
        const data = {
          'fileName': res
        }
        fileDeleteOss(data).then(response => {
          if (response.code == '200') {
            this.listNew.splice(index, 1)
            this.$modal.msgSuccess("删除成功");
          }
        });

      },
      fileChange(file, fileList) {
        this.xlsFile = fileList
      },
      submitUpload() {
        if(this.xlsFile.length<=0){
          this.$modal.msgSuccess("请先选取图片");
          return
        }
        const newArr = this.xlsFile.map(item => {
          return item.raw
        });
        let formData = new FormData();
        newArr.forEach((file, index) => {
          formData.append(`file[${index}]`, file);
        });
        uploadImages(formData).then(response => {
          if (response.code == '200') {
            let data = response.data
            if(this.isMultiple){
              this.listNew = [...this.listNew,...data]
            } else {
              this.listNew = data
              this.form.productUrl = this.listNew[0].url
            }
            this.xlsFile = []
            this.fileListN = []
          }
        });
      },
      handlePreviewN() {},
      handleRemoveN() {},
      beforeRemoveN() {},
      handle_successN(res) {
        console.log('图片上传成功')
      },
      handleExceedN() {},
      pictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      remove(file, fileList) {
        console.log(file, fileList)
      },

      // 图片上传
      // 上传前loading加载
      handleBeforeUpload(file) {
        let isImg = false;
        if (this.fileType.length) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          isImg = this.fileType.some(type => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
        } else {
          isImg = file.type.indexOf("image") > -1;
        }

        if (!isImg) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
          return false;
        }
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传图片，请稍候...");
        this.number++;
      },
      // 文件个数超出
      handleExceed() {
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
      },
      // 上传成功回调
      handleUploadSuccess(res, file) {
        if (res.code === 200) {
          this.uploadList.push({
            name: res.fileName,
            url: res.fileName
          });
          this.uploadedSuccessfully();
        } else {
          this.number--;
          this.$modal.closeLoading();
          this.$modal.msgError(res.msg);
          this.$refs.imageUpload.handleRemove(file);
          this.uploadedSuccessfully();
        }
      },
      // 删除图片
      handleDelete(file) {
        const findex = this.fileList.map(f => f.name).indexOf(file.name);
        if (findex > -1) {
          this.fileList.splice(findex, 1);
          this.$emit("input", this.listToString(this.fileList));
        }
      },
      // 上传失败
      handleUploadError() {
        this.$modal.msgError("上传图片失败，请重试");
        this.$modal.closeLoading();
      },
      // 上传结束处理
      uploadedSuccessfully() {
        if (this.number > 0 && this.uploadList.length === this.number) {
          this.fileList = this.fileList.concat(this.uploadList);
          this.uploadList = [];
          this.number = 0;
          this.$emit("input", this.listToString(this.fileList));
          this.$modal.closeLoading();
        }
      },
      // 预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      // 对象转成指定字符串分隔
      listToString(list, separator) {
        let strs = "";
        separator = separator || ",";
        for (let i in list) {
          if (list[i].url) {
            strs += list[i].url.replace(this.baseUrl, "") + separator;
          }
        }
        return strs != '' ? strs.substr(0, strs.length - 1) : '';
      },




      /** 查询商品图片列表 */
      getList() {
        this.loading = true;
        listProductpic(this.queryParams).then(response => {
          this.productpicList = response.data;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          productId: null,
          productCode: null,
          productUrl: null,
          urlSort: null,
          picType: null,
          picField1: null,
          picField2: null,
          picField3: null,
          picField4: null,
          picField5: null,
          delFlag: null,
          crTime: null,
          upTime: null
        };
        this.resetForm("form");
        this.xlsFile=[];
        this.listNew=[];
        this.limitNum = 7
        this.isMultiple = true
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.productId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加商品图片";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const productId = row.productId || this.ids
        getProductpic(productId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改商品图片";
          this.limitNum = 1
          this.isMultiple = false
          this.listNew.push({url:this.form.productUrl})
        });
      },
      /** 提交按钮 */
      submitForm() {
        // 更新   productUrl
        // 新增   productUrlList
        if (this.form.productId != null) {
          // 修改
          updateProductpic(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          const newArr = this.listNew.map(item => {
            return item.url
          });
          this.form.productUrlList = newArr
          // 新增
          if (this.listNew.length <= 0) {
            this.$modal.msgError("请上传文件");
            return
          }
          this.$refs["form"].validate(valid => {
            if (valid) {
              addProductpic(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          });
        }

        // this.$refs["form"].validate(valid => {
        //   if (valid) {
        //     if (this.form.productId != null) {
        //       updateProductpic(this.form).then(response => {
        //         this.$modal.msgSuccess("修改成功");
        //         this.open = false;
        //         this.getList();
        //       });
        //     } else {
        //       addProductpic(this.form).then(response => {
        //         this.$modal.msgSuccess("新增成功");
        //         this.open = false;
        //         this.getList();
        //       });
        //     }
        //   }
        // });

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const productIds = row.productId || this.ids;
        this.$modal.confirm('是否确认删除商品图片编号为"' + productIds + '"的数据项？').then(function() {
          return delProductpic(productIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('store/productpic/export', {
          ...this.queryParams
        }, `productpic_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style scoped lang="scss">
  // .el-upload--picture-card 控制加号部分
  ::v-deep.hide .el-upload--picture-card {
    display: none;
  }

  // 去掉动画效果
  ::v-deep .el-list-enter-active,
  ::v-deep .el-list-leave-active {
    transition: all 0s;
  }

  ::v-deep .el-list-enter,
  .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
  }

  .image-list {
    list-style-type: none;
    margin: 0px;
    padding: 0px;
    display: flex;
    flex-wrap: wrap;

    li {
      width: 150px;
      height:150px;
      margin-right: 3%;
      position: relative;

      span {
        position: absolute;
        right: 0px;
        top: 0px;
        cursor: pointer;
      }
    }
  }
</style>
